//
//  CommonMessage.m
//  integration_test
//
//  Created by mateng on 2024/2/19.
//

#import "CommonMessage.h"
#import "DataSyncHelper.h"

@interface CommonMessage ()

@property(nonatomic, strong) NSDictionary *notificationApps;

- (void)initNotificationApps;
- (void)closeAllNofications;

@end

@implementation CommonMessage

- (id)initWithHandler:(UTEPedEventHandler *)handler
{
    self = [super initWithHandler:handler];
    if (self) {
        [self initNotificationApps];
    }
    return self;
}

- (void)initNotificationApps {
    self.notificationApps = [NSDictionary dictionaryWithObjectsAndKeys:
                             @(UTEAppQQ), @"com.tencent.mobileqq",
                             @(UTEAppWechat), @"com.tencent.mm",
                             @(UTEAppInstagram), @"com.instagram.android",
                             @(UTEAppYouTube), @"com.google.android.youtube",
                             @(UTEAppFacebook), @"com.facebook.katana",
                             @(UTEAppTwitter), @"com.twitter.android",
                             @(UTEAppWhatsApp), @"com.whatsapp",
                             @(UTEAppSkype), @"com.skype.raider",
                             @(UTEAppLine), @"jp.naver.line.android",
                             @(UTEAppFacebookMessenger), @"com.facebook.orca",
                             @(UTEAppLinkedin), @"com.linkedin.android",
                             @(UTEAppViber), @"com.viber.voip",
                             @(UTEAppKakaoTalk), @"com.kakao.talk",
                             @(UTEAppVKontakte), @"com.vkontakte.android",
                             @(UTEAppSnapchat), @"com.snapchat.android",
                             @(UTEAppGmail), @"com.google.android.gm",
                             @(UTEAppFlickr), @"com.flickr.android",
                             @(UTEAppTumblr), @"com.tumblr",
                             @(UTEAppPinterest), @"com.pinterest",
                             @(UTEAppiOSOther),@"app_remind_other",
                             nil];
}

- (void)closeAllNofications {
    
    NSMutableArray *appArray = [NSMutableArray array];
    for (id key in self.notificationApps.allKeys) {
        NSNumber *appId = self.notificationApps[key];
        UTEModelANCSInfo *model = [UTEModelANCSInfo new];
        model.appId = [UTEDeviceMgr getBundleIDFromApp:[appId integerValue]];
        model.enable = 0;
        
        [appArray addObject:model];
    }
    [[UTEDeviceMgr sharedInstance] setNotifyAppListModel:appArray block:^(NSInteger errorCode, NSDictionary *uteDict) {
        NSLog(@"setNotifyAppListModel...%ld", errorCode);
    }];
}

- (NSString *)getPath {
    return @"common";
}

- (BOOL) methodCallConsumed:(NSString*)method params:(NSDictionary*)params result:(FlutterResult)result
{
    BOOL consumed = YES;
    if ([super methodCallConsumed:method params:params result:result])
        return YES;
    
    assert(method != nil);
    NSNumber *enable = nil;
    NSNumber *number = nil;
    if ([method isEqualToString:@"setLogEnable"]) {
        enable = [params objectForKey:KEY_ENABLE];
        [[SPHelper shareInstance] putObject:@"setLogEnable" value:enable];
        UTELogType logType = UTELogTypeNone;
        if ([enable boolValue]) {
            logType = UTELogTypePrintAndSave;
        }
        [[RYUTELogTool sharedInstance] setLogType:logType];
        result(@YES);
    }
    else if ([method isEqualToString:@"checkNotificationEnable"]) {
        result(@YES);
    }
    else if ([method isEqualToString:@"syncData"]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        [[DataSyncHelper shareInstance] fetchDataAsync];
        [self syncTimeClock:^(NSInteger errorCode, NSDictionary * _Nonnull uteDict) {
        }];
        result(@YES);
    }
    else if ([method isEqualToString:M_setSyncDataEnable]) {
        result(@YES);
    }
    else if ([method isEqualToString:M_setLogFileEnable]) {
        result(@YES);
    }
    else if ([method isEqualToString:@"removeData"]) {
        NSString *address = [params objectForKey:KEY_ADDRESS];
        if (address != nil) {
            [[DeviceHelper shareInstance] onDeviceDisconnect:address];
            result(@YES);
        }
        result(@NO);
    }
    else if ([method isEqualToString:@"setNotificationEnable"]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        NSString *packageName = [params objectForKey:KEY_PACKAGE];
        if ([packageName isEqualToString:@"app_close_all"]) {
            [self closeAllNofications];
            result(@YES);
        }
        else {
            number = [params objectForKey:KEY_ENABLE];
            if (packageName != nil) {
                NSNumber *appId = [self.notificationApps objectForKey:packageName];
                UTEModelANCSInfo *model = [UTEModelANCSInfo new];
                model.appId = [UTEDeviceMgr getBundleIDFromApp:[appId integerValue]];
                model.enable = [number boolValue] ? 1 : 0;
                
                NSArray *appArray = [NSArray arrayWithObjects:model, nil];
                [[UTEDeviceMgr sharedInstance] setNotifyAppListModel:appArray block:^(NSInteger errorCode, NSDictionary *uteDict) {
                    result(errorCode == UTEDeviceErrorNil ? @YES : @NO);
                }];
            }
            else {
                result(@YES);
            }
        }
    }
    else if ([method isEqualToString:@"exitApp"]) {
        result(@YES);
    }
    else if ([method isEqualToString:@"getAppInfo"]) {
        NSString* appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
//        appName = NSLocalizedStringFromTableInBundle(@"CFBundleDisplayName", @"InfoPlist", [NSBundle mainBundle], comment);
        NSString* packageName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
        NSString* versionCode = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        NSString* versionName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        
        result([NSDictionary dictionaryWithObjectsAndKeys:
               appName, @"appName",
               packageName, @"packageName",
               versionCode, @"versionCode",
               versionName, @"versionName",
               nil]);
    }
    else if ([method isEqualToString:M_checkBT3]) {
        result(@YES);
    }
    else if ([method isEqualToString:M_setDeviceFilter]) {
        NSNumber *filterNumber = [params objectForKey:KEY_ENABLE];
        if (filterNumber != nil) {
            [[SPHelper shareInstance] putObject:M_setDeviceFilter value:filterNumber];
        }
        result(@YES);
    }
    else if ([method isEqualToString:M_useDatabaseByName]) {
        NSString *dbName = [params objectForKey:KEY_NAME];
        if (dbName != nil) {
            [[SPHelper shareInstance] putObject:M_useDatabaseByName value:dbName];
        }
        result(@YES);
    }
    else if ([method isEqualToString:M_setLanguage]) {
        NSNumber *language = [params objectForKey:KEY_LANGUAGE];
        NSNumber *units = [params objectForKey:KEY_UNITS];
        if (language != nil && [self isConnected]) {
            [[UTEDeviceMgr sharedInstance] setLanguageEnum:[language integerValue] unit: [units integerValue] block:^(NSInteger errorCode, NSDictionary *uteDict) {
                result(errorCode == UTEDeviceErrorNil ? @YES : @NO);
            }];
        }
        else {
            result(@NO);
        }
    }
    else if ([method isEqualToString:M_queryDeviceSupportLanguage]) {
        if (![self isConnected]) {
            result([NSArray array]);
            return YES;
        }
        [[UTEDeviceMgr sharedInstance] readSupportLanguage:^(NSArray<NSNumber *> *array, NSInteger errorCode) {
            if (errorCode == UTEDeviceErrorNil) {
                result(array);
            }
            else {
                result([NSArray array]);
            }
        }];
    }
    else if ([method isEqualToString:@"preferredLanguages" ]) {
        result([NSLocale preferredLanguages]);
    }
    else if([method isEqualToString:@"currentLocale"]){
        NSString *locale = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];
        NSString *language = [NSLocale preferredLanguages][0];
        if(locale == nil) {
            NSString *formattedStr = [NSString stringWithFormat:@"%@",language];
            result(formattedStr);
        } else {
            NSString *formattedStr = [NSString stringWithFormat:@"%@-%@",language, locale];
            result(formattedStr);
        };
    }
    else if ([method isEqualToString:@"getNativeValue"]) {
        NSString *name = [params objectForKey:KEY_NAME];
        NSString *value = [params objectForKey:KEY_VALUE];
        result([[SPHelper shareInstance] getObject:name defaultValue:value]);
    }
    else if ([method isEqualToString:@"getNativeProp"]) {
        NSString *name = [params objectForKey:KEY_NAME];
        if ([@"is24HourFormat" isEqualToString:name]) {
            result([self getTimeDisplay] == 1 ? @NO : @YES);
        }
        else {
            result(@YES);
        }
    }
    else {
        consumed = NO;
    }
    
    return consumed;
}

@end
